package com.binguo.thirdPay.jinHuaSZFPay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.thirdPay.MD5Util;
import com.google.common.collect.Lists;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author yuritian
 * @Title: jinHuaSZFPayService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2020-02-0316:34
 */
@Service
public class JinHuaSZFPayService {

    private final String URL = "http://data.huafcy.com";

    private final String KEY = "9c0251e227a082817909eba28c828534";

    public static void main(String[] args) {
        JinHuaSZFPayService service = new JinHuaSZFPayService();
        String timestamp = System.currentTimeMillis()+"";
        service.pay("eyJpZGVudGlmaWVyIjoiOTgwOTYwMzUiLCJ0eXBlIjozfQ==","1","yunPengTest123123zz12","20200206228417717",timestamp);
    }

    public JSONObject pay(String content,
                          String amount,
                          String orderNo,
                          String merchantIdentifier,
                          String timestamp){
        JSONObject payResult;

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("amount",amount);
        map.put("orderNo",orderNo);
        map.put("timestamp",timestamp);
        String signBefore = "";
        int index = 0;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            signBefore += (index == 0 ? "" : "&") + entry.getKey() + "=" + entry.getValue();
            index++;
        }
        signBefore += "&key=" + KEY;
        System.out.println(signBefore);
        String sign = MD5Util.MD5Lower32(signBefore);
        System.out.println(sign);
        map.put("signature",sign);
        map.put("content",content);
        map.put("merchantIdentifier",merchantIdentifier);
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(URL+"/front/qrCode/third/explain", requestBody, String.class);
        String result = resp.getBody();
        System.out.println(result);
        payResult = JSONObject.parseObject(result);

        return payResult;
    }
}
